package tech.daoxuan.security.core.social.qq.api.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;
import tech.daoxuan.security.core.social.qq.api.QQ;
import tech.daoxuan.security.core.social.qq.api.QQUserInfo;

import java.io.IOException;

/**
 * @ClassName QQImpl
 * @Description TODO
 * @Author 10983
 * @Date 2019/6/22 23:02
 * @Version 1.0
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {

    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;

    private String openId;

    Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 工具类 ，把json字符串 转换为对象
     */
    private ObjectMapper objectMapper=new ObjectMapper();

    /**
     * @param accessToken 外部获取 需要传入
     * @param appId       实现申请好的，需要在配置文件中 配置 ，也需要传入
     */
    public QQImpl(String accessToken, String appId) {
        //调用 父类的方法，会 自动处理 accessToken，挂载到请求上
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;
        String url = String.format(URL_GET_OPENID, accessToken);
        String result = getRestTemplate().getForObject(url, String.class);
        logger.info(result);
        this.openId= StringUtils.substringBetween(result,"\"openid\":","}");
    }


    @Override
    public QQUserInfo getUserInfo()  {
        String url =String.format(URL_GET_USERINFO,appId,openId);
        String result=getRestTemplate().getForObject(url,String.class);
        logger.info(result);
        try {
            return  objectMapper.readValue(result,QQUserInfo.class);
        } catch (IOException e) {
           throw  new RuntimeException("运行时异常");
        }
    }
}
